package house;

public class HouseManagement {
	private House[] houses;

	public HouseManagement() {
		this.houses = new House[10];
	}

	public HouseManagement(int size) {
		this.houses = new House[size];
	}

	public boolean save(House house) {
	
		int index = getUseFulIndex();
		if (-1 == index) {
			return false;
		} else {
			houses[index] = house;
			return true;
		}
	}

	public boolean delete(House house) {
		for (int i = 0; i < houses.length && null != houses[i]; i++) {
			if (houses[i].getId() == house.getId()) {
				int j;
				for (j = 0; j < houses.length; j++) {
					houses[j-1] = houses[j];
					
				}
				houses[j-1]=null;
				return true;
			}
		}
		return false;
	}

	public boolean rent(House house) {
		
		for (int i = 0; i < houses.length && houses[i] != null; i++) {
			if(house.getId() == houses[i].getId()){
				if(!houses[i].isRent()){
					houses[i].setRent(true);
					return true;
				}
			}
		}
		return false;
	}

	public boolean back(House house) {
		int index = getUseFulIndex();
		for (int i = 0; i < index; i++) {
			if (house.getId() == houses[i].getId() && houses[i].isRent()) {
				houses[i].setRent(false);
				return true;
			}
		}
		return false;
	}

	public House[] selectAll() {

		return houses;
	}

	public House[] selectByPrice(int low, int high) {
		House[] house2 = new House[10];
		for (int i = 0 , j = 0; i < houses.length && null != houses[i]; i++) {
			if(houses[i].getPrice()>=low && houses[i].getPrice()<=high){
				 house2[j++] = houses[i];
			}
		}
		return house2;
	}

	public House[] selectByType(String type) {
		House[] house2 = new House[houses.length];
		int index = getUseFulIndex();
		for(int i = 0, j = 0; i<index; i++){
			if(houses[i].getType().equals(type)){
				house2[j++] = houses[i];
			}
		}
		return house2;
	}

	public House[] selectByLocation(String location) {
		House[] houses2 = new House[houses.length];
		int index = getUseFulIndex();
		for (int i = 0,j = 0; i < index; i++) {
			if (location.equals(houses[i].getLocation())) {
				houses2[j++] = houses[i];
			}
		}
		return houses2;
	}

	private int getUseFulIndex() {
		
		for (int i = 0; i < houses.length; i++) {
			if (null == houses[i]) {
				return i;
			}
		}
		return -1;
	}
}
